package com.zxt.mybatis.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;
import com.zxt.mybatis.utils.IDGenerator;
import com.zxt.security.bean.LoginUser;
import com.zxt.security.utils.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;

import java.time.LocalDateTime;

/**
 * mybatis-plus 自动填充字段
 *
 * @author zxt
 */
public class FieldMetaObjectHandler implements MetaObjectHandler {
    private final static String CREATE_TIME = "createTime";
    private final static String CREATE_BY = "createBy";
    private final static String UPDATE_TIME = "updateTime";
    private final static String UPDATE_BY = "updateBy";
    private final static String ORG_ID = "orgId";
    private final static String VERSION = "version";
    private final static String DELETED = "isDeleted";

    @Override
    public void insertFill(MetaObject metaObject) {
        LoginUser user = SecurityUtils.getLoginUser();
        // 创建者
        strictInsertFill(metaObject, CREATE_BY, Long.class, user.getId());
        // 创建时间
        strictInsertFill(metaObject, CREATE_TIME, LocalDateTime.class, LocalDateTime.now());
        // 更新者
        strictInsertFill(metaObject, UPDATE_BY, Long.class, user.getId());
        // 更新时间
        strictInsertFill(metaObject, UPDATE_TIME, LocalDateTime.class, LocalDateTime.now());
        // 创建者所属机构
        //strictInsertFill(metaObject, ORG_ID, Long.class, user.getOrgId());
        // 版本号
        //strictInsertFill(metaObject, VERSION, Integer.class, 0);
        // 删除标识
        //strictInsertFill(metaObject, DELETED, Integer.class, 0);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        LoginUser user = SecurityUtils.getLoginUser();
        // 更新者
        strictInsertFill(metaObject, UPDATE_BY, Long.class, user.getId());
        // 更新时间
        strictInsertFill(metaObject, UPDATE_TIME, LocalDateTime.class, LocalDateTime.now());
    }

    /**
     * 重写主键生成 使用雪花算法
     *
     * @return
     */
    @Bean
    public IdentifierGenerator idGenerator() {
        return new IDGenerator();
    }
}